<?php

// Admin template helpers
function omeka_addons_get_management_url($page, $action=null, $id=null)
{
    $url = 'admin.php?page='.$page;
    
    if($action) {
        $url .= '&amp;action='.$action;
    }
    
    if($id) {
        $url .= '&amp;id='.$id;
    }
    
    return $url; 
}

// Functions to get addons and versions
function omeka_addons_get_addons($type=null, $parameters = array(), $withVersions = true, $limit=null)
{
    global $wpdb;
	$addons_table = $wpdb->prefix . "addons";
	$versions_table = $wpdb->prefix . "versions";
	
	$sql = "SELECT DISTINCT a.id, a.addon_description, a.addon_name, a.directory_name FROM " . $addons_table . " a";
	if($withVersions) {
	    $sql .= " JOIN ". $versions_table . " v ON a.id = v.addon_id";
	}
	
	if($type == 'plugin' || $type == 'theme'){
	    $sql .= " WHERE a.type = '".$type."'"; 
	}
	
	if(count($parameters) > 0) {
	    foreach($parameters as $key => $value) {
	        if ($value != '') {
	            if($key == 'tag')
	            
    	        $sql .= " AND v.".$key." = '".$value."'";
            }
	    }
	}
	
	$sql .= " ORDER BY a.directory_name";
	if($limit) {
	    $sql .= " LIMIT ".$limit;
	}
	
    $results = $wpdb->get_results($sql, OBJECT);

    return $results;
}

function omeka_addons_get_featured_addons($type = null, $limit = 2)
{
    global $wpdb;
	$addons_table = $wpdb->prefix . "addons";

	$sql = "SELECT * FROM " . $addons_table . " WHERE featured = 1";
	
	if($type == 'plugin' || $type == 'theme'){
	    $sql .= " AND type = '".$type."'"; 
	}

	if($limit) {
	    $sql .= " LIMIT ".$limit;
	}
	
    $results = $wpdb->get_results($sql, OBJECT);

    return $results;
}

function omeka_addons_get_addon_by_id($id)
{
    global $wpdb;
	$table_name = $wpdb->prefix . "addons";
	$sql = "SELECT * FROM " . $table_name . " WHERE id=".$id;
	return $wpdb->get_row($sql, OBJECT);
}

function omeka_addons_get_addon_by_version_id($versionId)
{
    global $wpdb;
	$sql = "SELECT * FROM " . $wpdb->prefix . "addons a INNER JOIN (" . $wpdb->prefix . "versions v) ON (a.id = v.addon_id) WHERE v.id = '" .  $versionId . "'";
	return $wpdb->get_row($sql, OBJECT);
}

function omeka_addons_get_addon_by_name($name)
{
    global $wpdb;
	$table_name = $wpdb->prefix . "addons";
	$sql = "SELECT * FROM " . $table_name . " WHERE directory_name='".$name."'";
	return $wpdb->get_row($sql, OBJECT);
}

function omeka_addons_get_addons_by_tag($tagName)
{
	global $wpdb;
	
	$sql = "SELECT DISTINCT a.id, a.addon_description, a.addon_name, a.directory_name FROM " . $wpdb->prefix . "addons a";
	$sql .= " INNER JOIN (" . $wpdb->prefix . "addons_tags at, " . $wpdb->prefix . "addons_taggings ats) ON (ats.tag_id = at.id AND a.id = ats.addon_id) WHERE at.name = '" . $tagName . "'";
    return $wpdb->get_results($sql, OBJECT);
}

function omeka_addons_get_tags_for_addon($addonId)
{
	global $wpdb;
	
	$sql = "SELECT DISTINCT at.name FROM ". $wpdb->prefix . "addons_tags at INNER JOIN (" . $wpdb->prefix . "addons a, " . $wpdb->prefix . "addons_taggings ats) ON (ats.tag_id = at.id AND a.id = ats.addon_id) WHERE a.id = '" . $addonId . "'";
	return $wpdb->get_results($sql, OBJECT);
}

function omeka_addons_get_version_by_id($versionId)
{
	global $wpdb;
	$sql = "SELECT * FROM " . $wpdb->prefix . "versions WHERE id = '" . $versionId . "'";
	return $wpdb->get_row($sql, OBJECT);
}

function omeka_addons_get_latest_addon_version($addonId)
{
    $versions = omeka_addons_get_versions($addonId);
    return $versions[0];
}

function omeka_addons_add_addon_tags($addonId, $version, $tagNames, $type)
{
    global $wpdb;

    $addon = omeka_addons_get_addon_by_id($addonId);
	$type = $addon->type;

	// check if plugin version the highest version # for an addon in the db
	$versions = omeka_addons_get_versions($addonId);

	// if highest version number:
	if ($versions[0]->addon_id == $addonId) {			
		// look through tags for addon
		$tagArray = explode(',', $tagNames);
		foreach ($tagArray as $tag) {
			$tag = trim($tag);
			
			if ($tag != null) {
				// retrieve the tag object
				$table_name = $wpdb->prefix . "addons_tags";
				$sql = "SELECT * from " . $table_name . " WHERE name= '" . $tag . "'";
				$tagrow =  $wpdb->get_row($sql, OBJECT);
			
				if (!$tagrow) {
					// insert new tag
					$sql = "INSERT INTO " . $wpdb->prefix . "addons_tags SET name = '" . $tag . "'";
				    $wpdb->query($sql);
			
					// retrieve the tag object for your new spiffy tag
					$table_name = $wpdb->prefix . "addons_tags";
					$sql = "SELECT * from " . $table_name . " WHERE name= '" . $tag . "'";
					$tagrow =  $wpdb->get_row($sql, OBJECT);
				}
			
				// link the tags to the addons
				$sql = "INSERT INTO " . $wpdb->prefix . "addons_taggings SET addon_id = '" . $addonId . "', tag_id = '" . $tagrow->id . "', type = '" . $type . "'";
			    $wpdb->query($sql);
			}
		}
	}
}

function omeka_addons_delete_zip_file($version, $addon)
{
	$zipFilesPath = OMEKA_ADDONS_ZIP_FILES_PATH;

	$zipFilesCommand = "rm -rf " . $zipFilesPath . $addon->type . 's/' . $addon->directory_name . "-" . $version->tag_directory . ".zip ";

	shell_exec($zipFilesCommand);
}

function omeka_addons_delete_addon_tags($addonId, $versionId)
{
    global $wpdb;

	// select rows from taggings that reference specific addon
	$sql = "SELECT * FROM " . $wpdb->prefix . "addons_taggings WHERE addon_id = '" . $addonId . "'";
	$taggings = $wpdb->get_results($sql, OBJECT);	
	
	// foreach taggings associated with an addonId (each refers to a tag)
	foreach ($taggings as $tag) {
		// check to see if other addons use that tag (if tagId appears elsewhere in taggings table)
		$sql = "SELECT * FROM " . $wpdb->prefix . "addons_taggings" . "WHERE id '" . $tag->tag_id . "'";
		$results = $wpdb->get_row($sql, OBJECT);

		// delete reference in taggings table where $addonId and $tag->id match
		$wpdb->query("DELETE FROM " . $wpdb->prefix . "addons_taggings WHERE addon_id = '" . $addonId . "' AND tag_id = '" . $tag->id . "'");
		
		if (COUNT($results) == 0) {
			$wpdb->query("DELETE FROM " . $wpdb->prefix . "addons_tags WHERE id = '" . $tag->id . "'");
		}
	}
}

function omeka_addons_get_versions($addonId=null, $parameters = array(), $tagDirectory=true)
{
    global $wpdb;
	$table_name = $wpdb->prefix . "versions";
	$sql = "SELECT * from " . $table_name;
    
	if($addonId) {
	    $sql .= " WHERE addon_id=".$addonId;
	    if(count($parameters) > 0) {
    	    foreach ($parameters as $key => $value) {
               if ($value != '') {
                  $sql .= " AND $key = '".$value ."'";
               }
            }
        }
	}

	if($tagDirectory) {
	    $sql .= " ORDER BY tag_directory DESC";
	}
	
	return $wpdb->get_results($sql, OBJECT);
}

function omeka_addons_get_version_by_tag_directory($addonId, $tagDirectory)
{
    global $wpdb;
	$table_name = $wpdb->prefix . "versions";
	$sql = "SELECT * from " . $table_name . " WHERE tag_directory='".$tagDirectory."' AND addon_id='" . $addonId ."'";
	return $wpdb->get_row($sql, OBJECT);
}

// Functions to add/update/delete addons and version
function omeka_addons_create_addon() 
{
    global $wpdb;

    $directory = !empty($_REQUEST['directory_name']) ? $_REQUEST['directory_name'] : '';
    $type = !empty($_REQUEST['type']) ? $_REQUEST['type'] : '';
    $addonName = !empty($_REQUEST['addon_name']) ? $_REQUEST['addon_name'] : '';
    $addonDescription = !empty($_REQUEST['addon_description']) ? $_REQUEST['addon_description'] : '';

    if(omeka_addons_get_addon_by_name($directory)) {
        return '<div class="error"><p>An addon named '.$directory.' already exists.</p></div>';
    }
    $sql = "INSERT INTO " . $wpdb->prefix . "addons SET directory_name = '" . $directory . "', type = '" . $type . "', addon_name = '" . $addonName . "', addon_description = '" . $addonDescription . "'";
    $wpdb->query($sql);

    $sqlCheck = "SELECT id FROM " . $wpdb->prefix . "addons WHERE directory_name = '" . $directory . "' and type = '" . $type . "' LIMIT 1";

    $check = $wpdb->get_row($sqlCheck);
    if ( !empty($check) || !empty($check->id) ) { 
        echo '<div class="updated"><p>Addon create successfully.</p></div>';
    }
}

function omeka_addons_edit_addon($id)
{
    global $wpdb;

    $featured = !empty($_POST['featured']) ? $_POST['featured'] : 0;
    $addonName = !empty($_POST['addon_name']) ? $_POST['addon_name'] : '';
    $addonDescription = !empty($_POST['addon_description']) ? $_POST['addon_description'] : '';
    
    $sql = "UPDATE " . $wpdb->prefix . "addons SET featured = ". $featured . ", addon_name = '" . $addonName . "', addon_description = '" . $addonDescription . "' WHERE id = ".$id;
    $wpdb->query($sql);
    
    $sqlCheck = "SELECT * FROM " . $wpdb->prefix . "addons WHERE featured = '". $featured . "' AND addon_name = '" . $addonName . "' AND addon_description = '" . $addonDescription . "' LIMIT 1";
    
    $check = $wpdb->get_row($sqlCheck);
    if ( !empty($check) || !empty($check->id) ) { 
        // print_r($check);
        echo '<div class="updated"><p>Addon updated successfully.</p></div>';
    }
}

function omeka_addons_delete_addon($addonId)
{
    global $wpdb;
    if($addonId) {
        $wpdb->query("DELETE FROM " . $wpdb->prefix . "versions WHERE addon_id = '" . $addonId . "'");
        $wpdb->query("DELETE FROM " . $wpdb->prefix . "addons WHERE id = '" . $addonId . "'");
    }
	
	$versions = omeka_addons_get_versions($addonId);
	
	foreach ($versions as $version) {
		omeka_addons_delete_zip_file($addonId, $version->id);
		omeka_addons_delete_addon_tags($addonId, $version->id);		
	}
}

function omeka_addons_create_version()
{
    global $wpdb;
    
    if (!empty($_REQUEST['link'])) {
        $link = $_REQUEST['link'];
    } elseif (!empty($_REQUEST['website'])) {
        $link = $_REQUEST['website'];
    } else {
        $link = '';
    }
    
    if(!empty($_REQUEST['name'])) {
        $name = $_REQUEST['name'];
    } elseif (!empty($_REQUEST['title'])) {
        $name = $_REQUEST['title'];
    } else {
        $name = '';
    }

    $addonId = !empty($_REQUEST['addon_id']) ? $_REQUEST['addon_id'] : '';
    $author = !empty($_REQUEST['author']) ? $_REQUEST['author'] : '';
    $version = !empty($_REQUEST['version']) ? $_REQUEST['version'] : '';
    $description = !empty($_REQUEST['description']) ? $_REQUEST['description'] : '';
    $omekaMinimumVersion = !empty($_REQUEST['omeka_minimum_version']) ? $_REQUEST['omeka_minimum_version'] : '';
    $omekaTestedUpTo = !empty($_REQUEST['omeka_tested_up_to']) ? $_REQUEST['omeka_tested_up_to'] : '';
    $tagDirectory = !empty($_REQUEST['tag_directory']) ? $_REQUEST['tag_directory'] : '';
	$tagNames = !empty($_REQUEST['tags']) ? $_REQUEST['tags'] : '';

    if(omeka_addons_get_version_by_tag_directory($addonId, $tagDirectory)) {
        return '<div class="error"><p>Version '.$tagDirectory.' already exists.</p></div>';
    }

    $sql = "INSERT INTO " . $wpdb->prefix . "versions SET addon_id = '" . $addonId . "', name = '" . $name . "', author = '" . $author . "', link = '" . $link . "', version = '" . $version . "', description = '" . $description . "', omeka_minimum_version = '" . $omekaMinimumVersion . "', omeka_tested_up_to = '" . $omekaTestedUpTo . "', tag_directory = '" . $tagDirectory . "'";
    
    $wpdb->query($sql);

    $sqlCheck = "SELECT id FROM " . $wpdb->prefix . "versions WHERE addon_id = '" . $addonId . "' and name = '" . $name . "' and author = '" . $author . "' and link = '" . $link . "' and version = '" . $version . "' and description = '" . $description . "' and omeka_minimum_version = '" . $omekaMinimumVersion . "' and omeka_tested_up_to = '" . $omekaTestedUpTo . "' and tag_directory = '" . $tagDirectory . "' LIMIT 1";

    $check = $wpdb->get_row($sqlCheck);
    
    if ( !empty($check) || !empty($check->id) ) { 
        echo '<div class="updated"><p>Version created successfully.</p></div>';
    }

	$addonZipFileName = omeka_addons_create_zip_file($addonId, $tagDirectory);

	omeka_addons_add_addon_tags($addonId, $version, $tagNames, $type);

    if ($addonZipFileName) {
        echo '<div class="updated"><p>Downloadable zip file <em>' . $addonZipFileName . '</em> created successfully.</p></div>';
    } else {
		echo '<div class="updated"><p>Unable to create <em>' . $addonZipFileName . '</em> release of this version.</p></div>';	
	}
}

function omeka_addons_delete_version($versionId)
{
    global $wpdb;
    $version = omeka_addons_get_version_by_id($versionId);
    $addon = omeka_addons_get_addon_by_version_id($versionId);
	
	$addonDirectoryName = $addon->directory_name;
	$addonId = $addon->id;
	$addonType = $addon->type;
	
	$tagDirectory = $version->tag_directory;
	
	// based upon the versionId, figure out the addonId
    if($versionId) {
        $wpdb->query("DELETE FROM " . $wpdb->prefix . "versions WHERE id = '" . $versionId . "'");
    }

    omeka_addons_delete_zip_file($version, $addon);
	omeka_addons_delete_addon_tags($addonId, $versionId);
}

function omeka_addons_create_zip_file($addonId, $tagDirectory)
{
	    $rootPath = OMEKA_ADDONS_SVN_PATH;

	    $addon = omeka_addons_get_addon_by_id($addonId);
	    $type = $addon->type;

	    $addonPath = $rootPath . $type. 's/';
		$addonPath .= $addon->directory_name.'/';

		// location of the plugin in SVN
		$addonPath .= 'tags/'.$tagDirectory;

		// location on server where to create temporary files
		$tempPath = '/tmp/omeka-addons/';

		// create and execute subversion export command
		$subversionExportCommand = 'svn export ' . $addonPath . ' ' . $tempPath.'/'.$addon->directory_name;
		shell_exec($subversionExportCommand);

		// declare var for location of addon zip files
		$zipFilesLocation = "/websites/omeka.org/files/";
        
		// create and execute command to zip files of previous SVN export
		$zipFilesCommand = "cd $tempPath; zip -r " . $zipFilesLocation . $type . 's/' . $addon->directory_name . "-" . $tagDirectory . ".zip " . $addon->directory_name;
		shell_exec($zipFilesCommand);
		
		// remove the temp directory after zipping the file, to prevent conflicts with future addon zips.
		$removeTempCommand = 'rm -Rf ' . $tempPath. '/' . $addon->directory_name;
		shell_exec($removeTempCommand);
		
		return $addon->directory_name . '-' . $tagDirectory . '.zip';
}

function omeka_addons_get_ini_data($addonId,$version=null)
{
    $rootPath = OMEKA_ADDONS_SVN_PATH;
    
    $addon = omeka_addons_get_addon_by_id($addonId);
    
    $type = $addon->type;
    
    $url = $rootPath . $type. 's/';
    $url .= $addon->directory_name.'/';
    if($version) {
        $url .= 'tags/'.$version.'/'.$type.'.ini';
    } else {
        $url .= 'trunk/'.$type.'.ini';
        
    }
    
    $ini_array = parse_ini_file($url, true);
    
    if(!empty($ini_array)) {
        return $ini_array;
    } else {
        echo '<p>No .ini file present to parse!</p>';
    }
}

function omeka_addons_get_repository_directories($type=null,$addonDirectory=null)
{
    $url = OMEKA_ADDONS_SVN_PATH;

    if($type) {
        $url .= $type.'s/';
        if($addonDirectory) {
            $url .= $addonDirectory.'/tags/';
        }
    }
    
    if($html = @file_get_contents($url)) {
        $dom = new DomDocument();
        if(@$dom->loadHtml($html)) {
            $xpath = new DomXpath($dom);
            if($nodes = $xpath->query("//li/a")) {
                $folders = array();
                foreach($nodes as $key => $node) {
                    if($key == 0) continue;
                    $folders[] = str_replace('/','', $node->getAttribute('href'));
                }
                return $folders;
            }
        }
    }
}

function omeka_addons_get_parameter($parameter = null)
{
    global $wp_query;
    
    if (!$parameter) {
        $parameter = 'addons';
    }
    if($value = $wp_query->query_vars[$parameter]) {
        return $value;
    }
}

function omeka_addons_get_download($version)
{
    $addonId = $version->addon_id;
    
    // echo $addonId; exit;
    $addon = omeka_addons_get_addon_by_id($addonId);
    $url = 'http://omeka.org/files/'.$addon->type.'s/'.$addon->directory_name.'-'.$version->tag_directory.'.zip';
    return $url;
}

function omeka_addons_get_anchor($addon)
{
    return get_option('home').DIRECTORY_SEPARATOR.OMEKA_ADDONS_BASE_URL.DIRECTORY_SEPARATOR.$addon->type.'s/#'.strtolower($addon->directory_name);
}

function omeka_addons_display_tags_for_addon($addon)
{
    if($addon) {
        $tags = omeka_addons_get_tags_for_addon($addon->id);
        if($tags) {
            $tagList = '<p><strong>Tags:</strong> ';
            $i = 1;
            foreach($tags as $tag) {
                $tagList .= '<a href="'.omeka_addons_link_to_tag($tag).'">'.$tag->name.'</a>';
                if($i != count($tags)) {
                    $tagList .= ', ';
                }
                $i++;
            }
            $tagList .= '</p>';
            return $tagList;
        }
    }
}

function omeka_addons_link_to_tag($tag) {
    $page = omeka_addons_get_parameter('addons');
    return get_option('home').DIRECTORY_SEPARATOR.OMEKA_ADDONS_BASE_URL.DIRECTORY_SEPARATOR.$page.DIRECTORY_SEPARATOR.'tag'.DIRECTORY_SEPARATOR.$tag->name;
}

function omeka_addons_get_browse_link($addonType)
{
    return get_option('home').DIRECTORY_SEPARATOR.OMEKA_ADDONS_BASE_URL.DIRECTORY_SEPARATOR.$addonType;
}

?>